// 目录

const Catalogue = require("../../model/catelogue/Catalogue")
const Chapter = require("../../model/catelogue/chapter")

// 引入外部模块 获取当前时间
const { getTime } = require("../../utils/gettime")

// const checkParams = (data) => {
//     if (!data) return { msg: "操作失败", code: "400" }
// }

let attributes = ["id", "title", "creator", "createdate", "updator", "update"]

// 根据id 查询目录
exports.getCatalogueById = async ({ id }) => {
    // try {
    id = Number(id)
    if (!id) return { msg: "获取失败 id is undefind", code: "400" }
    let res = await Catalogue.findOne({
        attributes,
        where: { id },
        include: [{
            model:Chapter,
            // required: false
        }]
    })
    if (res) return { msg: "获取成功", code: "200", data:res }
    return { msg: "获取失败", code: "400" }
    // } catch (err) { return { msg: "操作失败", code: "400", err } }
}

//  查询目录列表
exports.getCatalogueList = async () => {
    let res = await Catalogue.findAll({ attributes })
    if (res) return { msg: "查询成功", code: "200", data: res }
    return { msg: "查询失败", code: "400" }
}

// 添加目录
exports.createCatalogue = async ({ title, creator }) => {
    try {
        if (!title) return { msg: "添加失败 title is undefind", code: "400" }
        const newData = {}
        newData.title = title
        if (creator) newData.creator = creator
        newData.createdate = getTime()
        let isCreate = await Catalogue.create(newData)
        if (isCreate) return { msg: "添加成功", code: "200" }
        return { msg: "操作失败", code: "400" }
    } catch (err) { return { msg: "操作失败", code: "400", err } }
}

// 编辑目录
exports.editCatalogue = async ({ id, title, updator }) => {
    try {
        if (!id && !title) return { msg: "编辑失败 ID or TITLE is nudefind", code: "400" }
        let newData = {};
        if (updator) newData.updator = updator
        newData.update = getTime()
        newData.title = title
        let isUpdate = await Catalogue.update(newData, { where: { id } })
        if (isUpdate) {
            let res = await Catalogue.findOne({ attributes, where: { id } })
            return { msg: "编辑成功", code: "200", data: res }
        } else {
            return { msg: "操作失败", code: "400" }
        }
    } catch (err) { return { msg: "操作失败", code: "400", err } }
}

// 删除目录
exports.removeCatalogue = async ({ id }) => {
    let isRemove = await Catalogue.destroy({ where: { id } })
    if (isRemove) return { msg: "删除成功", code: "200" }
    return { msg: "删除失败", code: "400" }
}